package com.ljd.controller;


import com.ljd.entity.UcenterMember;
import com.ljd.entity.vo.LoginInfoVo;
import com.ljd.entity.vo.LoginVo;
import com.ljd.entity.vo.RegisterVo;
import com.ljd.service.UcenterMemberService;
import com.ljd.util.JwtUtils;
import com.ljd.util.R;
import com.ljd.util.vo.UcenterMemberVo;
import com.why.handler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author ljd
 * @since 2021-12-30
 */
@RestController
@RequestMapping("/ucenter/member")
//@CrossOrigin
@Api(description = "用户接口")
public class UcenterMemberController {

    @Autowired
    UcenterMemberService memberService;
    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo){
        String token = memberService.login(loginVo);
        if(!StringUtils.isEmpty(token)){
            return R.ok().data("token",token);
        }else{
            return R.error().message("登录失败");
        }
    }
    @ApiOperation(value = "用户注册")
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo){
        Boolean isSuccess = memberService.register(registerVo);
        if(isSuccess){
            return R.ok().message("注册成功");
        }else{
            return R.error().message("注册失败");
        }
    }
    @ApiOperation(value = "根据token获取用户信息用于前端显示")
    @GetMapping("auth/getLoginInfo")
    public R getLoginInfo(HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)){
            throw new GuliException(20001,"获取用户信息失败");
        }
        LoginInfoVo loginInfoVo = memberService.getLoginInfo(memberId);
        if(loginInfoVo==null){
            return R.error();
        }else{
            return R.ok().data("loginInfoVo",loginInfoVo);
        }

    }
    @ApiOperation(value = "根据用户id获取用户信息")
    @PostMapping("getUcenterMember/{id}")
    public UcenterMemberVo getUcenterMember(@PathVariable String id){
        UcenterMember member = memberService.getById(id);
        UcenterMemberVo ucenterMemberVo = new UcenterMemberVo();
        BeanUtils.copyProperties(member, ucenterMemberVo);
        return ucenterMemberVo;
    }
    @GetMapping("getRegisterCount/{day}")
    public R getRegisterCount(@PathVariable String day){
        Integer count = memberService.getRegisterCount(day);
        return R.ok().data("count",count);
    }
}

